<?
include_once (dirname(__FILE__) . '/inc.JCAT_Initialize.php');

if( !isset($argv[1]) or !preg_match('|^jj://([\w\-_]+):([^/]+)/?((.+))?$|i',$argv[1],$arrRes) )
{
	JCAT_Gtk::MessageDialog(JCAT_Language::Sentence('地址无效“%s”',$argv[1])) ;
	exit() ;
}

$sCommand = strtolower($arrRes[1]) ;
$sJID = strtolower($arrRes[2]) ;
$sCommandData = $arrRes[4] ;
if( preg_match('/^BASE64:(.*)$/i',$sCommandData,$argv2) )
{
	$sCommandData = base64_decode($argv2[1]) ;
}

// 检查 JID 的合法性
if( !JJ_Account::VerifyJabberAddress($sJID) )
{
	JCAT_Gtk::MessageDialog(JCAT_Language::Sentence('遇到无效的用户地址：“%s”',$sJID)) ;
	exit() ;
}

// 创建临时目录
if( !file_exists(ROOT_PATH.'Temp/') )
{
	mkdir(ROOT_PATH.'Temp/') ;
	chmod(ROOT_PATH.'Temp/',0777) ;
}

$aSetting = JJ_Setting::GetGlobalInstance() ;
$nHeartbeatTime = $aSetting->GetItem('/JJ','HeartbeatInterval') ;

$sCommandDir = NULL ;

// 查找当前用户目录
$aIterator = new JCAT_FSOIterator(ROOT_PATH.'Temp/',JCAT_FSOIterator::DIR|JCAT_FSOIterator::RETURN_PATH) ;
$aIterator->First() ;
while( !$aIterator->IsDone() )
{
	$sUserDir = $aIterator->Current() ;
	$sHeartbeatFile = $sUserDir.'/Heartbeat' ;
	
	if( is_file($sHeartbeatFile) and file_get_contents($sHeartbeatFile)>=time()-$nHeartbeatTime)
	{
		$sCommandDir = $sUserDir.'/Command/' ;
	}
	
	$aIterator->Next() ;
}

// 未开启 JJ
if(!$sCommandDir)
{
	$sCommandDir = ROOT_PATH.'Temp/Public/Command/' ;
	$bStartJJ = true ;
}

else
{
	$bStartJJ = false ;
}

// 写入命令临时文件
$sCommandDir.= $sCommand.'/' ;
if( !file_exists($sCommandDir) )
{
	mkdir($sCommandDir,0777,true) ;
	chmod($sCommandDir,0777) ;
}

file_put_contents($sCommandDir.$sJID,$sCommandData) ;

// 启动 JJ
if( $bStartJJ )
{
	$aJJ = JJ_MainController::GetGlobalInstance() ;
	$aJJ->MainRun() ;
}

?>